package com.ruoyi.business.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.business.dto.WxLoginDto;
import com.ruoyi.business.service.IMobileWechatService;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.MessageException;
import com.ruoyi.common.utils.http.HttpReqRespUtil;
import com.ruoyi.system.mapper.SysUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author liumaotong
 * @Description 微信相关Service
 * @Date 2024/1/6
 */
@Service
public class MobileWeChatServiceImpl implements IMobileWechatService {

    private static final Logger logger = LoggerFactory.getLogger(MobileWeChatServiceImpl.class);

    private static final String WECHATURL = "https://api.weixin.qq.com";
    /**
     * 小程序appId
     */
    private static final String APP_ID = "wx82600781cccb3a2a";

    /**
     * 小程序secret
     */
    private static final String APP_SECRET = "e289edffad69dab887f5513a5a7e6421";

    @Autowired
    private RedisCache redisCache;

    @Override
    public String getAccessToken() throws Exception {
        //查询一下redis 是否存有token 如果没有 则重新获取
        if(redisCache.hasKey(APP_ID) && null != redisCache.getCacheObject(APP_ID)){
            return (String)redisCache.getCacheObject(APP_ID);
        }
        String url = WECHATURL + "/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
        JSONObject resJson = HttpReqRespUtil.sendGet(url);
        if(null == resJson){
            throw new Exception("获取微信AccessToken失败，微信接口返回对象为空！");
        }
        String token = resJson.getString("access_token");
        Integer expiresIn = resJson.getInteger("expires_in");
        //加入redis缓存中
        redisCache.setCacheObject(APP_ID,token,expiresIn-120, TimeUnit.SECONDS);
        return token;
    }


    /**
     * @param loginDto
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Author liumaotong
     * @Description 微信登录
     * @Date 2024/1/7
     * @Param [loginDto]
     */
    @Override
    public Map<String, Object> wxLogin(WxLoginDto loginDto) throws Exception {

        String url = WECHATURL + "/sns/jscode2session?grant_type=authorization_code&&appid=" + APP_ID +
                "&secret=" + APP_SECRET + "&js_code=" + loginDto.getJsCode();
        JSONObject resJson = HttpReqRespUtil.sendGet(url);
        if(null == resJson){
            throw new Exception("登录失败，微信接口返回对象为空！");
        }

        Map<String,Object> resMap = new HashMap<>();
        resMap.put("openid",resJson.getString("openid"));
        resMap.put("session_key",resJson.getString("session_key"));
        resMap.put("unionid",resJson.getString("unionid"));
        resMap.put("errcode",resJson.getInteger("errcode"));
        resMap.put("errmsg",resJson.getString("errmsg"));

        return resMap;
    }


    /**
     * @param loginDto
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Author liumaotong
     * @Description 获取小程序登录用户手机号
     * @Date 2024/1/18
     * @Param [wechatInfo]
     */
    @Override
    public JSONObject getPhoneNumber(WxLoginDto loginDto) throws Exception {
        //获取token
        String accessToken = this.getAccessToken();
        //接口url
        String url = WECHATURL + "/wxa/business/getuserphonenumber?access_token=" + accessToken;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",loginDto.getCode());
        JSONObject resJson = HttpReqRespUtil.sendPost(url,jsonObject.toJSONString());
        return resJson;
    }
}
